﻿/*
 * 创建人：申永康
 * 创建时间：2022/8/16
 * 
 * *******************************************************************
 * 
 * 功能描述：部门服务
 * 
 * *******************************************************************
 * 修改履历：
 * 申永康 20220816 创建文件
 * 申永康 20220816 添加注释
 * 
 * *******************************************************************
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data;
using XfTechOAWeb.Dtos.Departments;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using Microsoft.EntityFrameworkCore;
using XfTechOAWeb.Dtos;
using AutoMapper;
using XfTechOAWeb.Data.Base;
using XfTechOAWeb.EFCore;

namespace XfTechOAWeb.Service
{
    /// <summary>
    /// 部门模块-应用服务实现类
    /// </summary>
    public class DepartmentService : IDepartmentService
    {
        /// <summary>
        /// 依赖注入
        /// </summary>
        private readonly IUnitOfWork _uow;  //工作单元接口
        private readonly IRepository<DepartmentsUser> _departUserRepository;
        private readonly IRepository<User> _userRepository;
        private readonly IDepartmentRepository _departmentRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="departUserRepository"></param>
        /// <param name="userRepository"></param>
        /// <param name="departmentRepository"></param>
        /// <param name="uow"></param>
        public DepartmentService(IRepository<DepartmentsUser> departUserRepository,
                                 IRepository<User> userRepository,
                                 IDepartmentRepository departmentRepository,
                                 IUnitOfWork uow)
        {
            _departUserRepository = departUserRepository;
            _userRepository = userRepository;
            _departmentRepository = departmentRepository;
            _uow = uow;
        }

        /// <summary>
        /// 为部门添加用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public int AddDepartmentsUser(AddDepartmentsUsersDto input)
        {
            return _departmentRepository.AddDepartmentsUser(input.DepId, input.UIds);
        }

        /// <summary>
        /// 部门删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Del(string ids)
        {
            string[] arrId = ids.Split(',');
            foreach (var id in arrId)
            {
                _departmentRepository.Remove(Convert.ToInt32(id));
            }

            return _departmentRepository.SaveChanges();
        }

        /// <summary>
        /// 部门返填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PageResponseModel<BackDepartmentDto> GetDepartment(int id)
        {
            var ls = from A in _departUserRepository.Table.Where(x => x.DepId == id)
                     join D in _userRepository.Table on A.UId equals D.UId
                     select new BackDepartmentDto
                     {
                         //uId = String.Join(',', (from B in db.Table join C in dbd.Table on B.DepId equals C.DepId where C.DepId == A.DepId select C.UId).ToArray()),
                         uId = D.UId.ToString(),
                         DepId = A.DepId,
                         Account = D.Account,
                         CreatedTime = D.CreatedTime,
                         Status = D.Status,
                         UName = D.UName,
                         roles = ""
                     };
            PageResponseModel<BackDepartmentDto> p = new PageResponseModel<BackDepartmentDto>()
            {
                TotalCount = ls.Count(),
                PageList = ls.ToList(),
            };
            return p;
        }

        /// <summary>
        /// 部门分页显示
        /// </summary>
        /// <param name="departmentPageDto"></param>
        /// <returns></returns>
        public PageResponseModel<DepartmentDto> DShow(DepartmentPageDto departmentPageDto)
        {
            var ls = from a in _departmentRepository.Table.Where(x => x.IsChecks == 0)
                     select
                     new DepartmentDto
                     {
                         Account = string.Join(',', (from B in _userRepository.Table
                                                     join C in _departUserRepository.Table on B.UId equals C.UId
                                                     where C.DepId == a.DepId
                                                     select B.UName)
                                                     .ToArray()),
                         DUId = a.DepId,
                         Name = a.Name,
                         ParentId = a.ParentId,
                         Status = a.Status,
                         CreatedTime = a.CreatedTime,
                         IsChecks = a.IsChecks,
                         DepId = a.DepId,
                         CascadeId = a.CascadeId,
                         PName = (from d in _departmentRepository.Table
                                  where a.ParentId == d.DepId
                                  select d.Name).SingleOrDefault() ?? "根节点",
                     };
            if (!string.IsNullOrEmpty(departmentPageDto.did))
            {
                ls = ls.Where(x => x.CascadeId.Contains(departmentPageDto.did));
            }
            if (!string.IsNullOrEmpty(departmentPageDto.names))
            {
                ls = ls.Where(x => x.Name.Contains(departmentPageDto.names));
            }

            PageResponseModel<DepartmentDto> p = new PageResponseModel<DepartmentDto>()
            {
                TotalCount = ls.Count(),
                PageList = ls.OrderBy(x => x.DepId)
                             .Skip((departmentPageDto.Pindex - 1) * departmentPageDto.Psize)
                             .Take(departmentPageDto.Psize)
                             .ToList(),
            };
            return p;
        }

        /// <summary>
        /// 返填数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Department GIt(int id)
        {
            return _departmentRepository.GetById(id);
        }

        /// <summary>
        /// 部门树形的显示
        /// </summary>
        /// <returns></returns>
        public List<Department> GetDepartTree()
        {
            var slist = _departmentRepository.Table.Where(x => x.ParentId == 0).ToList();
            ChildrenMshow(slist);
            return slist.Where(x => x.IsChecks == 0).ToList();
        }

        public ResponseModel<UptDepartmentsDto> Update(UptDepartmentsDto department)
        {
            if (department.ParentId != 0)
            {
                int maxCascadeId = _departmentRepository.Table.Where(x => x.ParentId == department.ParentId && department.CascadeId != x.CascadeId).Count();

                string d = (maxCascadeId + 1).ToString();

                department.CascadeId = _departmentRepository.Table.Where(x => x.DepId == department.ParentId).SingleOrDefault().CascadeId + $"{d}.";
            }

            //修改
            _departmentRepository.Upt(department);
            //实例化结果返回模型
            int res = _uow.SaveChanges();
            if (res > 0)
            {
                ResponseModel<UptDepartmentsDto> responseModel = new ResponseModel<UptDepartmentsDto>()
                {
                    Code = 200,
                    Msg = "修改成功!",
                    Data = department,
                };
                return responseModel;
            }
            else
            {
                ResponseModel<UptDepartmentsDto> responseModel = new ResponseModel<UptDepartmentsDto>()
                {
                    Code = 401,
                    Msg = "修改失败!",
                };
                return responseModel;
            }
        }

        /// <summary>
        /// 部门的停用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Upt(int id)
        {
            _departmentRepository.Upt(id);
            return _departmentRepository.SaveChanges();
        }

        /// <summary>
        /// 部门的添加
        /// </summary>
        /// <param name="department"></param>
        /// <returns></returns>
        public ResponseModel<AddDepartmentsDto> Add(AddDepartmentsDto department)
        {

            Department departments = new Department()
            {

                Name = department.Name,
                ParentId = department.ParentId,
                Status = department.Status
            };
            if (department.ParentId != 0)
            {
                string d = (_departmentRepository.Table.Where(x => x.ParentId == departments.ParentId).Count() + 1).ToString();
                departments.CascadeId = _departmentRepository.Table.Where(x => x.DepId == departments.ParentId).SingleOrDefault().CascadeId + $"{d}.";
            }
            else
            {
                string d = (_departmentRepository.Table.Where(x => x.ParentId == 0).Count() + 1).ToString();
                departments.CascadeId = $".0.{d}.";
            }

            //添加
            _departmentRepository.Insert(departments);
            //实例化结果返回模型
            int res = _departmentRepository.SaveChanges();
            if (res > 0)
            {
                ResponseModel<AddDepartmentsDto> responseModel = new ResponseModel<AddDepartmentsDto>()
                {
                    Code = 200,
                    Msg = "添加成功!",
                    Data = department,
                };
                return responseModel;
            }
            else
            {
                ResponseModel<AddDepartmentsDto> responseModel = new ResponseModel<AddDepartmentsDto>()
                {
                    Code = 401,
                    Msg = "添加失败!",
                };
                return responseModel;
            }
        }
        /// <summary>
        /// 调用的递归方法
        /// </summary>
        /// <param name="dd"></param>
        private void ChildrenMshow(List<Department> dd)
        {
            foreach (var item in dd)
            {
                item.Dlist = new List<Department>();
                item.Dlist = _departmentRepository.Table.Where(x => x.ParentId == item.DepId).ToList();
                ChildrenMshow(item.Dlist);
            }
        }
    }
}
